import streamlit as st
from webui_pages.utils import *
from streamlit_option_menu import option_menu
from webui_pages import *
import os
import base64
from configs.client_config import SERVER_HOST,SERVER_PORT,TIMEOUT_HTTPX

SERVER_ADDRESS=SERVER_HOST+':'+SERVER_PORT

#shy-2023-08-30
st.session_state= st.session_state
# shy-2023-08-30

# shy-2023-08-31
# no_remote_api=False时，会调用运行中的python api.py，所提供的api。若llm_api.py和api.py都被启动了，则本前端，可以顺利连接api.py所提供的api中的模型。
api = ApiRequest(base_url=SERVER_ADDRESS, no_remote_api=False,timeout=TIMEOUT_HTTPX)

# 从后端加载server_config
server_config = api.get_server_config()
if not len(server_config):
    st.error("无法连接后端！")
else:
    server_config = server_config[0]

if __name__ == "__main__":
    st.set_page_config(
        "LangChat-NJU",
        os.path.join("img", "chatchat_icon_blue_square_v2.png"),
        initial_sidebar_state="expanded",
        menu_items={
            'Get Help': 'https://github.com/chatchat-space/Langchain-Chatchat',
            'About': f"""欢迎使用 LangChat-NJU！"""
        }
    )


    if not chat_box.chat_inited:
        st.toast(
            f"欢迎使用 [`LangChat-NJU`] ! \n\n"
            f"当前使用模型`{server_config['LLM_MODEL']}`, 您可以开始提问了."
        )

    pages = {
        "对话": {
            "icon": "chat",
            "func": dialogue_page,
        },
        "知识库管理": {
            "icon": "hdd-stack",
            "func": knowledge_base_page,
        },
        "文档Agent": {
            "icon": "file",
            "func": file_agent_page,
        }
    }

    # shy-2023-08-31
    # 这里设定了sidebar的样子
    with st.sidebar:
        # st.image(
        #     os.path.join(
        #         "img",
        #         'njulogo.png'
        #     ),
        #     # use_column_width=True,
        # )

        # 以下代码使得njulogo.png在sidebar中居中，且宽度为50.
        image_path = os.path.join(
            "img",
            'njulogo.png'
        )
        st.markdown(
            f"""
            <div style="display: flex; justify-content: center;">
            <img src='data:image/png;base64,{base64.b64encode(open(image_path, "rb").read()).decode()}' style="width: 50px;">
            </div>                
            """,
            unsafe_allow_html=True
        )

        options = list(pages)
        icons = [x["icon"] for x in pages.values()]

        default_index = 0
        selected_page = option_menu(
            "",
            options=options,
            icons=icons,
            default_index=default_index,
        )

    if selected_page in pages:
        pages[selected_page]["func"](api,server_config)
